package com.ah.shanxi_demo.service.impl;

import com.ah.shanxi_demo.common.enums.SyncEnum;
import com.ah.shanxi_demo.entity.SxRegister;
import com.ah.shanxi_demo.entity.SxSync;
import com.ah.shanxi_demo.mapper.SxRegisterMapper;
import com.ah.shanxi_demo.mapper.SxSyncMapper;
import com.ah.shanxi_demo.service.ISyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.ah.shanxi_demo.sync.client.SyncClient.sync_client;

/**
 * @author zt 2020/8/21
 */
@Service
public class SyncService implements ISyncService {

    private static final Logger logger = LoggerFactory.getLogger(SyncService.class);

    @Autowired
    private SxSyncMapper syncMapper;

    @Autowired
    private SxRegisterMapper registerMapper;

    @Override
    @Transactional
    public SyncEnum stateSync() {

        //获取最新的同步表 的注册id 获取 省级节点编码与节点唯一标识
        SxSync sxSyncNew = syncMapper.selectRecent();

        //获取最新的关联注册表信息
        SxRegister sxRegister = registerMapper.selectById(sxSyncNew.getRegisterId());

        //调用部级同步信息接口
        SxSync syncResultModel = sync_client(sxRegister);

        if (null==syncResultModel){
            logger.error("SyncService【stateSync】fail");
            return null;
        }

        //判断部级平台返回省级节点编码与节点唯一标识 是否与上次相同 然后做不同的逻辑判断
        SyncEnum syncEnum = policy_order_same(syncResultModel, sxSyncNew);

        //同步表数据更新
        syncMapper.updateSync(syncResultModel);

        return syncEnum;
    }


    public SyncEnum policy_order_same(SxSync syncResultModel, SxSync sxSyncNew) {

        if (syncResultModel.getPolicyState().equals(sxSyncNew.getPolicyState())
                && syncResultModel.getWorkorderState().equals(sxSyncNew.getWorkorderState())) {
            return SyncEnum.SYNC;
        }

        if (!syncResultModel.getPolicyState().equals(sxSyncNew.getPolicyState())) {

            if (!syncResultModel.getWorkorderState().equals(sxSyncNew.getWorkorderState())) {
                return SyncEnum.POLICY_ORDER;
            }
            return SyncEnum.POLICY;
        } else {

            if (!syncResultModel.getWorkorderState().equals(sxSyncNew.getWorkorderState())) {
                return SyncEnum.ORDER;
            }
            return SyncEnum.SYNC;
        }
    }


}
